package com.zengde.ai_sandbox.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.zengde.ai_sandbox.config.OssConfiguration;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OssService {

    private final OSS ossClient;
    private final OssConfiguration ossConfiguration;
    private static final String TEMP_DIR = "temp/";
    private static final String PRODUCT_DIR = "product/";

    /**
     * 将文件上传到临时目录，有效期30分钟
     */
    public String uploadToTemp(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = TEMP_DIR + UUID.randomUUID().toString() + extension;

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(file.getContentType());
        metadata.setContentLength(file.getSize());
        
        // 设置30分钟后过期
        Date expiration = Date.from(LocalDateTime.now().plusMinutes(30).toInstant(ZoneOffset.UTC));
        metadata.setExpirationTime(expiration);

        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossConfiguration.getBucketName(),
                objectName,
                file.getInputStream(),
                metadata
        );

        ossClient.putObject(putObjectRequest);
        return objectName;
    }

    /**
     * 将文件从临时目录移动到永久目录
     */
    public void moveToProduct(String tempObjectName) {
        String productObjectName = tempObjectName.replace(TEMP_DIR, PRODUCT_DIR);
        
        // 复制文件到product目录
        ossClient.copyObject(
                ossConfiguration.getBucketName(),
                tempObjectName,
                ossConfiguration.getBucketName(),
                productObjectName
        );
        
        // 删除临时文件
        ossClient.deleteObject(ossConfiguration.getBucketName(), tempObjectName);
    }
} 